// axios 二次封装http  request  ajax
import axios from 'axios'
import Qs from 'qs'
// 提示插件
import { MessageBox } from 'element-ui'

// axios 全局配置
axios.defaults.withCredentials = true//axios 全局配置可跨域  true跨域 false不跨域

export default function (path, params, method = "get", headerType) {

  //  根据headerType 设置不同的 请求头

  let data = {}
  if (method == "post") {
    if (headerType == "json") {
      // json类型的请求头  {name:111,age:222}
      axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"
      data = params;
    } else if (headerType == "multipart") {
      data = params;
      // 上传文件等 需要的请求头
      axios.defaults.headers.post["Content-Type"] = "multipart/form-data"
    } else {
      // 表单形式的请求头 要把传入的json 序列化 name=1&age=2
      axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"
      data = Qs.stringify(params)
    }
  }
  // 请求拦截器
  axios.interceptors.request.use(config => {
    if (config.url == "/users/cart") {
      if (localStorage.token) {
        config.headers["token"] = localStorage.token;
        // config.headers["Authorization"] = 1989;  //权限的携带
      } else {
        location.href = "/login"
      }
    }
    return config
  })
  //响应拦截器
  axios.interceptors.response.use(response => {
    // if (response.data.success) {
    //   MessageBox.alert(response.data.success)
    // }
    // if (response.data.err) {
    //   MessageBox.alert(response.data.err)
    //   return false
    // }
    if (response.data.code == 700) {
      MessageBox.alert("暂无数据")
    }
    if (response.data.code == 500001) {
      MessageBox.alert("登录已过期")
    }
    return response
  })



  if (method == "get") {
    //  表单类型的请求头设置  name=111&age=222
    axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
    data = params;
  }

  return new Promise((resolve, reject) => {
    if (method == "get") {
      axios({
        url: path,
        params: data,
        method: "get",
        timeout: 6000
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    } else {
      axios({
        url: path,
        data: data,
        method: "post",
        timeout: 6000
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    }

  })


}